package com.Humanities.content.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xuecheng.base.exception.XueChengPlusException;
import com.Humanities.content.mapper.CourseBaseMapper;
import com.Humanities.content.mapper.TeachplanMapper;
import com.Humanities.content.mapper.TeachplanMediaMapper;
import com.xuecheng.content.model.dto.BindTeachplanMediaDto;
import com.xuecheng.content.model.dto.SaveTeachplanDto;
import com.xuecheng.content.model.dto.TeachplanDto;
import com.xuecheng.content.model.po.CourseBase;
import com.xuecheng.content.model.po.Teachplan;
import com.xuecheng.content.model.po.TeachplanMedia;
import com.Humanities.content.service.ITeachplanService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

import static cn.hutool.core.lang.Console.log;

/**
 * <p>
 * 课程计划 服务实现类
 * </p>
 *
 * @author ysj
 * @since 2025-03-26
 */
@Slf4j
@Service
public class TeachplanServiceImpl extends ServiceImpl<TeachplanMapper, Teachplan> implements ITeachplanService {
@Autowired
    TeachplanMapper teachplanMapper;
@Autowired
TeachplanMediaMapper teachplanMediaMapper;
    @Autowired
    private CourseBaseMapper courseBaseMapper;

    @Override
    public List<TeachplanDto> findTeachplanTree(Long courseId) {

        LambdaQueryWrapper<Teachplan> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Teachplan::getCourseId,courseId);
        queryWrapper.orderByAsc(Teachplan::getParentid);  // 排序，确保父节点在前
        queryWrapper.orderByAsc(Teachplan::getOrderby); // 再次排序，确保同级节点的顺序

        List<Teachplan> teachplanList = teachplanMapper.selectList(queryWrapper);
        // 2. 根据教学计划构建树形结构
        List<TeachplanDto> teachplanDtos = new ArrayList<>(); //最后返回的List
        for (Teachplan teachplan : teachplanList) {
            TeachplanDto teachplanDto = convertToDto(teachplan); // 实体类转换为Dto
            if (teachplan.getParentid() == 0) {
                teachplanDtos.add(teachplanDto); // 顶级节点
            } else {
//                addTeachplanNode(teachplanDtos, teachplanDto); // 其他节点
                for (TeachplanDto parentDto : teachplanDtos) {
                    // 如果父节点的 ID 匹配子节点的 parentId，说明它是该节点的父节点
                    if (parentDto.getId().equals(teachplanDto.getParentid())) {
                        parentDto.getTeachPlanTreeNodes().add(teachplanDto);
                    }
                }
            }
        }

        // 3. 返回树形结构的List<TeachplanDto>
        return teachplanDtos;
    }

    /**
     * 保存或者修改课程计划
     * @param teachplan
     */
    @Override
    public void saveOrUpdateTeachplanTree(SaveTeachplanDto teachplan) {
        Teachplan teachplan1 = BeanUtil.toBean(teachplan, Teachplan.class);
        if(teachplan1.getId() !=null ){
            //为修改操作
            teachplanMapper.updateById(teachplan1);
        }else {
            //保存操作
            //排序
            //取出同父同级别的课程计划数量
            LambdaQueryWrapper<Teachplan> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Teachplan::getCourseId,teachplan1.getCourseId());
            queryWrapper.eq(Teachplan::getParentid,teachplan1.getParentid());
            teachplan1.setOrderby(teachplanMapper.selectCount(queryWrapper)+1);
            teachplanMapper.insert(teachplan1);
        }
    }

    @Override
    @Transactional
    public void removeByIdNew(Long id) {
       //判断是否大章节
        Teachplan teachplan = teachplanMapper.selectById(id);
        if(teachplan.getGrade()==1){
            //判断大章节下是否有小章节
            LambdaQueryWrapper<Teachplan> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Teachplan::getParentid,id);
            int count = teachplanMapper.selectCount(queryWrapper);
            if(count>0){
                XueChengPlusException.cast("课程计划信息还有子级信息，无法操作");
            }else {
                //删除大章节
                teachplanMapper.deleteById(id);
            }
        }else {
            //删除小章节
            teachplanMapper.deleteById(id);
            teachplanMediaMapper.delete(new LambdaQueryWrapper<TeachplanMedia>().eq(TeachplanMedia::getTeachplanId,id));
        }
        }

    /**
     * 课程下移
     * @param id
     */
    @Override
    public void movedownTeachplan(Long id) {
        //判断大章节是否为最后一个或者章节总数只有一个
        Teachplan teachplan = teachplanMapper.selectById(id);
        //判断有无比此节点排序顺序大的节点
        LambdaQueryWrapper<Teachplan> queryWrapper1 = new LambdaQueryWrapper<>();
        queryWrapper1.eq(Teachplan::getCourseId,teachplan.getCourseId());
        queryWrapper1.eq(Teachplan::getParentid,teachplan.getParentid());
        queryWrapper1.gt(Teachplan::getOrderby,teachplan.getOrderby());
        log("查询结果为："+teachplanMapper.selectCount(queryWrapper1));
        if(teachplanMapper.selectCount(queryWrapper1)==0){
            XueChengPlusException.cast("已经是最后一个节点，无法下移");
        }

        LambdaQueryWrapper<Teachplan> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Teachplan::getCourseId,teachplan.getCourseId());
        queryWrapper.eq(Teachplan::getParentid,teachplan.getParentid());
        Integer count = teachplanMapper.selectCount(queryWrapper);
        if(count==1){
            XueChengPlusException.cast("只有一个节点，无法移动");
        }

        Teachplan nextTeachplan = teachplanMapper.selectOne(queryWrapper
                .eq(Teachplan::getOrderby, teachplan.getOrderby() + 1));  // 查找orderby值为当前节点加1的节点

        if (nextTeachplan != null) {
            // 交换当前节点和下一个节点的orderby值
            teachplanMapper.update(teachplan, new LambdaUpdateWrapper<Teachplan>()
                    .set(Teachplan::getOrderby, nextTeachplan.getOrderby())  // 当前节点的orderby设置为下一个节点的orderby
                    .eq(Teachplan::getId, teachplan.getId()));

            teachplanMapper.update(nextTeachplan, new LambdaUpdateWrapper<Teachplan>()
                    .set(Teachplan::getOrderby, teachplan.getOrderby())  // 下一个节点的orderby设置为当前节点的orderby
                    .eq(Teachplan::getId, nextTeachplan.getId()));
        }

    }
    /*

    * 删除大章节，大章节下有小章节时不允许删除。
2、删除大章节，大单节下没有小章节时可以正常删除。
3、删除小章节，同时将关联的信息进行删除。
如果失败返回：
{"errCode":"120409","errMessage":"课程计划信息还有子级信息，无法操作"}

如果成功：状态码200，不返回信息
     */
    @Override
    public void moveupTeachplan(Long id) {
        //判断章节是否为第一个或者章节总数只有一个
        Teachplan teachplan = teachplanMapper.selectById(id);
        if(teachplan.getOrderby()==1){
            XueChengPlusException.cast("当前为第一个节点，无法上移");
        }
        LambdaQueryWrapper<Teachplan> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Teachplan::getCourseId,teachplan.getCourseId());
        queryWrapper.eq(Teachplan::getParentid,teachplan.getParentid());
        Integer count = teachplanMapper.selectCount(queryWrapper);
        if(count==1){
            XueChengPlusException.cast("只有一个节点，无法移动");
        }
        if (teachplan.getOrderby() > 1) {
            // 查找当前节点的前一个节点，orderby - 1
            Teachplan prevTeachplan = teachplanMapper.selectOne(queryWrapper
                    .eq(Teachplan::getOrderby, teachplan.getOrderby() - 1)); // 查找orderby值为当前节点减1的节点

            if (prevTeachplan != null) {
                // 交换当前节点和前一个节点的orderby值
                teachplanMapper.update(teachplan, new LambdaUpdateWrapper<Teachplan>()
                        .set(Teachplan::getOrderby, prevTeachplan.getOrderby())
                        .eq(Teachplan::getId, teachplan.getId()));

                teachplanMapper.update(prevTeachplan, new LambdaUpdateWrapper<Teachplan>()
                        .set(Teachplan::getOrderby, teachplan.getOrderby())
                        .eq(Teachplan::getId, prevTeachplan.getId()));
            }
        }
    }

    @Override
    public TeachplanMedia associationMedia(BindTeachplanMediaDto bindTeachplanMediaDto) {
        //根据课程计划查询课程的id
        Teachplan teachplan = teachplanMapper.selectById(bindTeachplanMediaDto.getTeachplanId());
        if(teachplan==null){
            XueChengPlusException.cast("教学计划不存在");
        }
        Integer grade = teachplan.getGrade();
        if(grade!=2){
            XueChengPlusException.cast("只允许第二级教学计划绑定媒资文件");
        }

        // 1. 先删除之前的绑定关系
        LambdaQueryWrapper<TeachplanMedia> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(TeachplanMedia::getTeachplanId, bindTeachplanMediaDto.getTeachplanId());
        teachplanMediaMapper.delete(queryWrapper);

        // 2. 插入新的绑定关系
        TeachplanMedia teachplanMedia = new TeachplanMedia();
        BeanUtil.copyProperties(bindTeachplanMediaDto, teachplanMedia);
        teachplanMedia.setMediaFilename(bindTeachplanMediaDto.getFileName());

        teachplanMedia.setCourseId(teachplan.getCourseId());
        teachplanMedia.setCreateDate(LocalDateTime.now());
        teachplanMediaMapper.insert(teachplanMedia);

        return teachplanMedia;



    }

    @Override
    public void unassociationMedia(Long teachPlanId, String mediaId) {
        //根据课程计划查询课程的id
        Teachplan teachplan = teachplanMapper.selectById(teachPlanId);
        if(teachplan==null){
            XueChengPlusException.cast("教学计划不存在");
        }
        Integer grade = teachplan.getGrade();
        if(grade!=2){
            XueChengPlusException.cast("只允许第二级教学计划解绑媒资文件");
        }
        // 1. 删除绑定关系
        LambdaQueryWrapper<TeachplanMedia> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(TeachplanMedia::getTeachplanId, teachPlanId);
        queryWrapper.eq(TeachplanMedia::getMediaId, mediaId);
        teachplanMediaMapper.delete(queryWrapper);
    }


    /**
     * 转换 Teachplan 为 TeachplanDto
     * @param teachplan
     * @return TeachplanDto
     */
    private TeachplanDto convertToDto(Teachplan teachplan) {
        TeachplanDto teachplanDto = new TeachplanDto();
        BeanUtil.copyProperties(teachplan, teachplanDto);
        LambdaQueryWrapper<TeachplanMedia> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(TeachplanMedia::getTeachplanId, teachplan.getId());
        // 获取媒资信息
        TeachplanMedia teachplanMedia = teachplanMediaMapper.selectOne(queryWrapper);
        teachplanDto.setTeachplanMedia(teachplanMedia);

        // 查找子节点
        List<TeachplanDto> childNodes = new ArrayList<>();
        teachplanDto.setTeachPlanTreeNodes(childNodes);

        return teachplanDto;
    }

//    /**
//     * 将子节点添加到父节点的树形结构中
//     * @param teachplanDtos
//     * @param teachplanDto
//     */
//    private void addTeachplanNode(List<TeachplanDto> teachplanDtos, TeachplanDto teachplanDto) {
//        for (TeachplanDto parentDto : teachplanDtos) {
//            addChildNode(parentDto, teachplanDto);
//        }
//    }
//
//    /**
//     * 将子节点添加到某个父节点的树形结构中
//     * @param parentDto
//     * @param teachplanDto
//     */
//    private void addChildNode(TeachplanDto parentDto, TeachplanDto teachplanDto) {
//        // 如果父节点的 ID 匹配子节点的 parentId，说明它是该节点的父节点
//        if (parentDto.getId().equals(teachplanDto.getParentid())) {
//            parentDto.getTeachPlanTreeNodes().add(teachplanDto);
//            return;
//        }
//        // 如果没有找到父节点，递归查找
//        for (TeachplanDto childNode : parentDto.getTeachPlanTreeNodes()) {
//            addChildNode(childNode, teachplanDto);
//        }
//    }
}